package com.jy.appmarket.screenlock.view;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.jy.appmarket.R;
import com.jy.appmarket.screenlock.adapter.MessageAdapter;
import com.jy.appmarket.screenlock.model.MessageModel;
import com.jy.appmarket.screenlock.view.SwipeDismissListView.OnDismissCallback;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.provider.Telephony;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

/**
 * 类说明：
 * 
 * @author jie.li
 * @date 2015-4-7
 * @version 1.0
 */
public class MessageView extends LinearLayout {

	private Context mContext;
	private View mContentView;
	private SwipeDismissListView mListView;
	private static List<MessageModel> mList;
	private MessageAdapter mAdapter;
	private MessageListener mMessageListener;
	private ImageView mRemoveIv;

	public MessageView(Context context) {
		super(context);
		mContext = context;
		initData();
		initView();
	}

	public MessageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		initData();
		initView();
	}
	
	private void initData(){
		if (mList == null) {
			mList = new ArrayList<MessageModel>();
		}
	}

	public void setMessageViewListener(MessageListener listener) {
		mMessageListener = listener;
	}

	public interface MessageListener {
		void onMessageClick(MessageModel info);
	}

	public void addMessage(MessageModel model) {
		if (mList == null) {
			mList = new ArrayList<MessageModel>();
		}
		boolean isExist = false;
		for (MessageModel m : mList) {
			if (model.getAppPkg().equals(m.getAppPkg())) {
				if(model.getAppName()!=null && (model.getAppName().equals("toolbox_sms") || model.getAppName().equals("toolbox_phone"))){
					m = model;
				}else{
					m.setNotification(model.getNotification());
					int count = m.getNotificationCount() + 1;
					m.setNotificationCount(count);
					m.setContent(mContext.getString(R.string.app_message_tip, count));
					m.setStartTime(model.getStartTime());
				}

				isExist = true;
				break;
			}
		}
		if (!isExist) {
			mList.add(0, model);
		}
		updateView();
	}

	public void removeMessageView() {
		if(mList!=null){
			mList.clear();
		}
		updateView();
	}

	public void updateView() {
		if (mList == null) {
			return;
		}
		if (mList.size() > 0) {
			Collections.sort(mList, new Comparator<MessageModel>() {
				@Override
				public int compare(MessageModel lhs, MessageModel rhs) {
					return lhs.getStartTime() > rhs.getStartTime() ? -1 : 1;
				}
			});
			mRemoveIv.setVisibility(View.VISIBLE);
		} else {
			mRemoveIv.setVisibility(View.GONE);
		}
		if(mAdapter != null){
			mAdapter.notifyDataSetChanged();
		}
	}

	private void initView() {
		mContentView = LayoutInflater.from(mContext).inflate(
				R.layout.view_message, this);
		mListView = mContentView
				.findViewById(R.id.swipeDismissListView);
		mRemoveIv = mContentView.findViewById(R.id.remove_image);
		mRemoveIv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				removeMessageView();
			}
		});

		mAdapter = new MessageAdapter(mContext, mList);
		if (mList.size() > 0) {
			mRemoveIv.setVisibility(View.VISIBLE);
		} else {
			mRemoveIv.setVisibility(View.GONE);
		}

		mListView.setAdapter(mAdapter);

		mListView.setOnDismissCallback(new OnDismissCallback() {

			@Override
			public void onDismiss(int dismissPosition) {
				if (mMessageListener != null && dismissPosition != -1) {
					try {
						mMessageListener.onMessageClick((MessageModel) mAdapter
								.getItem(dismissPosition));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});

	}

	public void addSMSMessage(int count, long time, String address) {
		if (mList != null && count > 0) {
			String name = "toolbox_sms";
			String pkg = getSMSPkg() != null ? getSMSPkg() : "";
			String content = mContext
					.getString(R.string.sms_message_tip, count);
			addMessage(name, pkg, content, time, address);
		}
	}

	public void addPhoneMessage(int count, long time) {
		if (mList != null && count > 0) {
			String name = "toolbox_phone";
			String pkg = "com.android.contacts";
			String content = mContext.getString(R.string.phone_message_tip,
					count);
			addMessage(name, pkg, content, time, null);
		}
	}

	public void addMessage(String appName, String pkg, String content, long time, String extra) {
		if (mList != null) {
			MessageModel model = new MessageModel();
			model.setAppName(appName == null ? "" : appName);
			model.setAppPkg(pkg == null ? "" : pkg);
			model.setContent(content == null ? "" : content);
			model.setStartTime(time);
			model.setExtra(extra == null ? "" : extra);
			addMessage(model);
		}
	}
	public void addMessage(String appName, String pkg, String content, long time, String extra,  Notification notification) {
		if (mList != null) {
			MessageModel model = new MessageModel();
			model.setAppName(appName == null ? "" : appName);
			model.setAppPkg(pkg == null ? "" : pkg);
			model.setContent(content == null ? "" : content);
			model.setStartTime(time);
			model.setExtra(extra == null ? "" : extra);
			if (notification != null) {
				model.setNotification(notification);
			}
			addMessage(model);
		}
	}
	public void addMessage(String appName, String pkg, int resId, long time, String extra,  Notification notification) {
		if (mList != null) {
			MessageModel model = new MessageModel();
			model.setAppName(appName == null ? "" : appName);
			model.setAppPkg(pkg == null ? "" : pkg);
			model.setContent(resId == -1 ? "" : mContext.getString(resId, 1));
			model.setStartTime(time);
			model.setNotificationCount(1);
			model.setExtra(extra == null ? "" : extra);
			if (notification != null) {
				model.setNotification(notification);
			}
			addMessage(model);
		}
	}

	@SuppressLint("NewApi")
	private String getSMSPkg() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			String defaultSmsPkg = Telephony.Sms.getDefaultSmsPackage(mContext
					.getApplicationContext());
			if (defaultSmsPkg != null) {
				return defaultSmsPkg;
			}
		} else {
			// 4.4以下的手机，对于原生android系统，将环聊通知拦截
			// 获取短信的包名
			String androidOrigin = "com.google.android.talk";
			Set<String> smsPkgNameSet = getSmsPkgName(mContext);

			if (smsPkgNameSet != null) {
				for (String str : smsPkgNameSet) {
					boolean systemApp = isSystemApp(mContext, str);
					if (systemApp) {
						if (smsPkgNameSet.contains(androidOrigin)) {
							return androidOrigin;
						} else {
							return str;
						}
					}
				}
			}
		}
		return null;
	}

	private Set<String> getSmsPkgName(Context context) {
		PackageManager sPackageManager = context.getPackageManager();
		Intent smsIntent = new Intent();
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			smsIntent.setAction("android.provider.Telephony.SMS_DELIVER");// 4.4以上
		} else {
			smsIntent.setAction("android.provider.Telephony.SMS_RECEIVED");
		}
		List<ResolveInfo> resolveInfos = sPackageManager
				.queryBroadcastReceivers(smsIntent,
						PackageManager.GET_RECEIVERS);
		int size = resolveInfos.size();
		if (size < 1) {
			return null;
		}
		Set<String> result = new HashSet<String>();
		for (int i = 0; i < size; i++) {
			String packageName = resolveInfos.get(i).activityInfo.packageName;
			result.add(packageName);
		}
		return result;
	}

	// 判断是否为系统应用
	private boolean isSystemApp(Context context, String packageName) {
		try {
			PackageInfo mPackageInfo = context.getPackageManager()
					.getPackageInfo(packageName, 0);
			if ((mPackageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
				return false;
			}
		} catch (PackageManager.NameNotFoundException e) {
		}
		return true;
	}
}
